from typing import Optional

import pdfplumber

from ai_translator_v2.book import Book, Content, ContentType, Page, TableContent
from ai_translator_v2.utils import LOG
from .exceptions import PageNotOfRangeException


class PDFParser:
    @staticmethod
    def parse(file_path: str, pages: Optional[int] = None) -> Book:
        book = Book(pdf_file_path=file_path)
        with pdfplumber.open(file_path) as pdf:
            if pages is not None and pages > len(pdf.pages):
                raise PageNotOfRangeException(len(pdf.pages), pages)

            if pages is None:
                pdf_pages = pdf.pages
            else:
                pdf_pages = pdf.pages[:pages]
            for pdf_page in pdf_pages:
                page = Page()
                raw_text = pdf_page.extract_text()
                tables = pdf_page.extract_tables()
                # Remove empty lines and leading/trailing whitespace
                for table in tables:
                    for row in table:
                        for cell in row:
                            raw_text = raw_text.replace(cell, "", 1)

                if raw_text:
                    raw_text_lines = raw_text.splitlines()
                    cleaned_text = 'n'.join([line.strip() for line in raw_text_lines if line.strip()])
                    text_content = Content(content_type=ContentType.TEXT, original=cleaned_text)
                    page.add_content(text_content)
                    LOG.debug(f"[raw_text]\n{cleaned_text}")
                if tables:
                    table = TableContent(tables)
                    page.add_content(table)
                    LOG.debug(f"[table]\n{table}")
                book.add_page(page)
            return book

    @staticmethod
    def pdfplumber_parser(file_path, pages: Optional[int] = None):
        pass


if __name__ == '__main__':
    pdf_parser = PDFParser.parse('../../tests/test.pdf')
